public member function
<memory>

std::unique_ptr::operator[]

element_type& operator[](size_t i) const;  // only defined in array-specialization
Offset access
Returns a reference to the i-th object (zero-based) in the managed array.

The size of the array pointed by the stored pointer shall be greater than i.

It is equivalent to: get()[i].

This member function is exclusive of the array-specialization of unique_ptr (unique_ptr<T[],D>). The non-specialized version does not include it.

Parameters

i
Index of the element to be accessed (zero-based).
size_t is an unsigned integral type.

Return value

A reference to the ith object in the managed array.
element_type is a member type, defined as an alias of unique_ptr's first template parameter.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// unique_ptr::operator[]
#include <iostream>
#include <memory>

int main () {
  std::unique_ptr<int[]> foo (new int[5]);

  for (int i=0; i<5; ++i) foo[i] = i;

  for (int i=0; i<5; ++i) std::cout << foo[i] << ' ';
  std::cout << '\n';

  return 0;
}

Output:
0 1 2 3 4 


See also